<script setup lang="ts">
// import { computed, inject, Ref, ref } from 'vue';
import { TodosApi } from '../../api';
// import { useSubjectStore, Observer } from '../../stores/subject.store';
// import TodoEditDialog from '../../components/dialog/TodoEditDialog.vue';
// const subjectStore = useSubjectStore();
// let dialog = inject('dialog_todo_ref') as Ref<InstanceType<typeof TodoEditDialog>>;


// let todos = ref<Todo[]>([]);
let route = useRoute();
console.log("query:",route.query)
let query_title = route.query.title?.toString()??'';
let query_page = parseInt(route.query.page?.toString()??'1')
let query_status = route.query.completed?.toString()??'all';
let query_completed = query_status === 'true'? 1 : query_status === 'false'? 0 : undefined;

let title = ref('');
let status = ref<TodoStatus>('all');
let currentPage = ref(query_page); // 当前页码
let totalPages = ref(1); // 总页数
const page_display_count = ref(10); // 限制显示的页码数量

let completed = computed(() => {
  return status.value === 'true' ? 1 : status.value === 'false' ? 0 : undefined;
});


const { data: res } = await useAsyncData("todos",()=>TodosApi.getTodos(query_title, query_completed, query_page));
console.log("objects,",res.value?.data)
let todos = ref(res.value?.data.items || []);
totalPages.value = res.value?.data.pages || 1;
page_display_count.value = res.value?.data.pageSize || 10;

// const observer = new Observer('todos', async (msg) => {
//   console.log("todosview,", msg);
//   if (msg === 'todo updated') {
//     await fetchData(currentPage.value);
//   } else {
//     currentPage.value = 1; // 重置到第一页
//     await fetchData();
//   }
// });
// subjectStore.attach(observer);






async function fetchData(page = 1) {
  try {
    console.log("todosview,", "fetchData");
    let res = await TodosApi.getTodos(title.value, completed.value, page);
    todos.value = res.data.items;
    totalPages.value = res.data.pages;
    page_display_count.value = res.data.pageSize;
  } catch (error) {
    console.error('获取待办事项失败:', error);
  }
}

// 初始化时加载第一页数据
// fetchData();

//handlerSubmit
async function handlerSubmit(e: Event) {
  e.preventDefault();
  currentPage.value = 1; // 搜索时重置到第一页
  await fetchData();
}

//handlerEdit
async function handlerEdit(todo: Todo) {
//   dialog.value!.open(todo);
}


//handlerPage
async function handlerPage(page: number) {
//   $event.stopPropagation();
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
  await fetchData(page);
}

// 计算要显示的页码范围
const displayedPages = computed(() => {
  let startPage = Math.max(currentPage.value - Math.floor(page_display_count.value / 2), 1);
  let endPage = startPage + page_display_count.value - 1;
  if (endPage > totalPages.value) {
    endPage = totalPages.value;
    startPage = Math.max(endPage - page_display_count.value + 1, 1);
  }
  return Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);
});
</script>

<template>
  <div>
    <dl>
      <dt class="flex">
        <span class="">最新待办</span>
        <form class="flex grow justify-end gap-2" @submit.prevent="handlerSubmit">
          <input type="text" name="title" v-model="title" class="border">
          <select name="status" id="" v-model="status">
            <option value="all">所有</option>
            <option value="true">已完成</option>
            <option value="false">未完成</option>
          </select>
          <button type="submit">搜索</button>
          <button type="button" @click="fetchData()">刷新</button>
        </form>
      </dt>
      <dd v-for="todo in todos" class="flex border-b gap-x-2">
        <span class="grow">{{ todo.title }}</span>
        <span>{{ todo.completed ? '已完成' : '未完成' }}</span>
        <span><NuxtLink :to="'/todo/'+todo.id">查看</NuxtLink></span>
        <span><button @click="handlerEdit(todo)">编辑</button></span>
      </dd>
      <!-- 分页 -->
      <dd class="pt-2 pb-1">
        <ul class="flex justify-end gap-1 [&>li]:p-1 [&>li]:border [&>li]:cursor-pointer">
          <!-- 上一页按钮 -->
          <li :class="{ 'bg-gray-200': currentPage === 1 }" @click.capture="handlerPage(currentPage - 1)"
            :disabled="currentPage === 1">
            <NuxtLink :to="`/todos?page=${currentPage - 1}&title=${title}&status=${status}`">上一页</NuxtLink>
            <!-- 上一页 -->
          </li>
          <!-- 页码循环 -->
          <li v-for="page in displayedPages" :key="page" :class="{ 'bg-gray-200': page === currentPage }"
            @click.capture="handlerPage(page)">
            <!-- {{ page }} -->
            <NuxtLink :to="`/todos?page=${page}&title=${title}&status=${status}`">
              {{ page }}    
            </NuxtLink>
          </li>
          <!-- 下一页按钮 -->
          <li :class="{ 'bg-gray-200': currentPage === totalPages }" @click="handlerPage(currentPage + 1)"
            :disabled="currentPage === totalPages">
            <!-- 下一页 -->
            <NuxtLink :to="`/todos?page=${currentPage + 1}&title=${title}&status=${status}`">下一页</NuxtLink>
          </li>
        </ul>
      </dd>
    </dl>
  </div>
</template>

<style scoped></style>